const baiduMap = Symbol('baiduMap');

var BMap = require('baidumap');

module.exports = appProto => {

    class BaiduMap {
    
        constructor(config) {
            this.bmap = BMap.create(config);
        }

        wrap(name, opts) {
            return new Promise((fulfill, reject) => {
                return this.bmap[name](opts, (err, result) => {
                    if (err) {
                        return reject(err);
                    }
                    if (typeof result === 'string') {
                        try {
                            result = JSON.parse(result);
                        } catch (e) {
                            return reject(e);
                        }
                    }
                    if (result.status !== 0) {
                        console.error('BaiduMap status error', result.status, result);
                        const e = new Error(`BaiduMap status error ${result.status}`);
                        e.code = result.status;
                        return reject(e);
                    }
                    return fulfill(result.result);
                });
            });
        }

        reverseGeocoder(opts) {
            return this.wrap('reverseGeocoder', opts);
        }
    }
    

    Object.defineProperty(appProto, 'baiduMap', {
        get() {
            if (!this[baiduMap]) {
                if (!this.config.baiduMap.appKey) {
                    throw new Error('config.baiduMap.appKey is required for use baidu map api, provide it in config file or BMAP_APP_KEY env');
                }
                this[baiduMap] = new BaiduMap({ ak: this.config.baiduMap.appKey });
            }
            return this[baiduMap];
        }
    });
}
